/*******************************************************************************
*  file    : devicestatusboard.cpp
*  created : 30.08.2013
*  author  : Slyshyk Oleksiy (alexSlyshyk@gmail.com)
*******************************************************************************/

#include "devicestatusboard.hpp"
#include "ui_devicestatusboard.h"
#include "devicemodel.hpp"
#include <QDebug>
#include <QTableWidgetItem>
#include <QTimer>

#include <qlogger.hpp>
namespace{
QLogger* l = QLoggerEngine::getLogger("core");
}

DeviceStatusBoard::DeviceStatusBoard(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::DeviceStatusBoard)
{
    ui->setupUi(this);
    ui->label   ->setText("");
    ui->label_2 ->setText("");
    ui->label_3 ->setText("");
    ui->map_link->setText("");
    ui->map_date->setText("");

    ui->tableWidget->setColumnCount(3);
    QStringList header;
    header<<tr("Запрос")<<tr("Отправлен")<<tr("В работе");
    ui->tableWidget->setHorizontalHeaderLabels(header);

    upd_timer_ = new QTimer(this);
    connect(upd_timer_, SIGNAL(timeout()), this, SLOT(onUpdateTime()) );
    upd_timer_->start(60000);
}

DeviceStatusBoard::~DeviceStatusBoard()
{
    delete ui;
}
QAbstractItemModel* DeviceStatusBoard::model() const
{
    return model_.data();
}

void DeviceStatusBoard::setModel(QAbstractItemModel* model)
{
    model_ = model;
}

void DeviceStatusBoard::currentChanged(const QModelIndex& current, const QModelIndex& previous)
{
    Q_UNUSED(previous);

    if(!model_)
        return;
    current_ = current;
    if(!current_.isValid())
        {
            logError(l)<<QStringLiteral("Невалидный индекс.");
            return;
        }

    updateCurrentData();
}

void DeviceStatusBoard::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight,
                                    const QVector<int> &roles)
{
    if( (!topLeft.isValid()) || (!bottomRight.isValid()))
        return;

    if(  (topLeft.row()     <= current_.row())  &&
         (bottomRight.row() >= current_.row())     )
        {
            updateCurrentData();
        }

    Q_UNUSED(roles)
}

void DeviceStatusBoard::updateCurrentData()
{
    QString link = current_.data(DM_LAST_POS_ROLE).toString().remove(QChar(0x0d));
    ui->map_link->setText(QString("<a style='text-decoration:none' href=\"%1\">%1</a>").arg(link));
    QString link_date =
            current_.model()->data(current_.model()->index(current_.row(),DM_LAST_POS_DATE_IDX)).toString();
    if(link_date.size())
        ui->map_date->setText(QString("[%1]").arg(link_date));
    else
        ui->map_date->setText("");

    QString state = current_.data(DM_LAST_INFO_ROLE).toString();
    state.replace("SIGNAL",tr("Сигнал"));
    state.replace("BAT",tr("Батарея"));
    state.replace("MODE",tr("Режим"));
    QStringList states = state.split(";");
    if(states.size() == 9)
        {
//  0   1        2              3               4       5     6            7
//Krot;V.3;352964051552355;13.01.00 07:55:49;MODE: 1;GSM: +;SIGNAL: 80%;BAT: 100%
            ui->label  ->setText(QString("Sleeper %1 %2"  ).arg(states[1]).arg(states[2]));
            ui->label_2->setText(QString("%1, %2"         ).arg(states[4]).arg(states[5]));
            ui->label_3->setText(QString("%1, %2"         ).arg(states[6]).arg(states[7]));
        }
    else if(states.size() == 12)
        {
//  0   1        2              3               4       5     6            7       8           9       10
//Krot;V.3;352964051552355;02.10.13 10:03:00;MODE: 3;GSM: +;GPRS: +;SIGNAL: 67%;INTERNET: +;ONLINE: +;BAT: 100%
            ui->label  ->setText(QString("Sleeper %1 %2"  ).arg(states[1]).arg(states[2]));
            ui->label_2->setText(QString("%1, %2, %3, %4, %5" )
                                                                .arg(states[4]).arg(states[5])
                                                                .arg(states[6]).arg(states[8])
                                                                .arg(states[9]));
            ui->label_3->setText(QString("%1, %2"         ).arg(states[7]).arg(states[10]));
        }
    else
        {
            ui->label->setText("");
            ui->label_2->setText("");
            ui->label_3->setText("");
            logError(l)<<QString(tr("Неизвестный формат INFO (%1 части(ей))")).arg(states.size());
        }


    QStringList tasks = current_.data(DM_WORKING_TASKS).toString().split("\n");
    ui->tableWidget->setRowCount(0);
    for(const QString& str : tasks)
        {
            QStringList line = str.split("?");
            if(line.size() == 2)
                {
                    int row = ui->tableWidget->rowCount();
                    ui->tableWidget->setRowCount(row + 1);
                    QTableWidgetItem * item = 0;
                    item = new QTableWidgetItem(line.at(0));
                    ui->tableWidget->setItem(row,0,item);

                    if(line.at(1).startsWith(QChar(':')))
                        line[1] = line[1].right(line[1].size()-1);
                    item = new QTableWidgetItem(line.at(1));
                    ui->tableWidget->setItem(row,1,item);

                    item = new QTableWidgetItem(" ");
                    ui->tableWidget->setItem(row,2,item);
                }
        }
    updateTimeElapse();

}

void DeviceStatusBoard::updateTimeElapse()
{
    for(int row = 0; row < ui->tableWidget->rowCount(); ++row)
        {
            QDateTime date = QDateTime::fromString(ui->tableWidget->item(row,1)->text(), "yyyy-MM-dd hh:mm:ss");
            qint64 secs_to = date.secsTo(QDateTime::currentDateTime());

            ui->tableWidget->item(row,2)->setText(QString("%1:%2:%3")
                                        .arg(secs_to/60/60,2,10,QChar('0'))
                                        .arg(secs_to/60%60,2,10,QChar('0'))
                                        .arg(secs_to%60   ,2,10,QChar('0')));
            if(secs_to > (24*60*60+30*60))//TODO - заменить прибитую гвоздями константу на настраиваемую
                for(int column = 0; column < ui->tableWidget->columnCount(); ++column)
                    ui->tableWidget->item(row,column)->setBackgroundColor(QColor("red"));
        }
}

void DeviceStatusBoard::onUpdateTime()
{
    updateTimeElapse();
}

